from QQLoginTool.QQtool import OAuthQQ
from django.shortcuts import render
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
# Create your views here.
from rest_framework.generics import CreateAPIView
from django.conf import settings
from django.shortcuts import render
from rest_framework import request
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from rest_framework_jwt.settings import api_settings
from django.conf import settings
from oauth.models import OAuthQQUser
from oauth.serizlizers import OAuthQQSerializer


class OAuthQQRLView(APIView):
    # 第一步：跳转页面
    def get(self,request):
        state = request.query_params.get('state')
        # http: // www.meiduo.site: 8080 / oauth_callback.html?code = 13BC41D97C346F72EBD69171F85D6660&state = % 2F
        # 假如没有没有绑定的话，就是url:http: // www.meiduo.site: 8080 / oauth_callback.html/
        if not state:
            state ='/'
        print(settings.BASE_DIR)
        # 创建对象，使用对象的属性，获取地址
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        url = oauth.get_qq_url()

        # 返回url
        return Response({
            'login_url':url
        })

class OAuthQQView(CreateAPIView):
     # 获取code
     # 4．保存数据，因为其中有CreateAPIView这个类里有post这个方法，而post又会设计到验证，因此，只需要序列化器就可以进行眼真
     # 创建一个需序列化器

    serializer_class = OAuthQQSerializer
    def get(self,request):

        #　1.获取code
        code = request.query_params.get('code')
        if not code:
            return Response({
                'message':'缺少code值',
            },status=status.HTTP_401_UNAUTHORIZED)

        # 2.通过code获取access_token，
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        access_token = oauth.get_access_token(code)


        # 3.通过access——token获取openid
        openid = oauth.get_open_id(access_token)

        # return Response()

        # 4.判断openid是否绑定
        try:
            qq_user = OAuthQQUser.objects.get(openid = openid)
        except:
            # 未绑定过
            tjs = TJS(settings.SECRET_KEY,300)
            token = tjs.dumps({'openid':openid}).decode()
            return Response({
                'access_token':token
            })


        # openid加密


        # 绑定过openid    通过外键　两个表的联合，对应生成对象　th_users & th_users_qq
        user = qq_user.user

        # 生成token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return Response({
            'username':user.username,
            'user_id':user.id,
            'token':token

        })















